//微信or余额支付
var wxPay = true;
var balancePay = false;
$("#balance_pay").click(function() {
    $('#balance_pay .iconfont').css('display', 'block');
    $('.weixin_pay .iconfont').css('display', 'none');
    wxPay = false;
    balancePay = true;
})
$(".weixin_pay").click(function() {
        $('#balance_pay .iconfont').css('display', 'none');
        $('.weixin_pay .iconfont').css('display', 'block');
        wxPay = true;
        balancePay = false;
    })
    //知道商品价格则不能用余额支付
$("#go_back").click(function() {
    window.location.href = document.referrer;
})

$("#recharge").click(function() {
        window.location.href = "../html/recharge.html";
    })
    //订单数据buyData
    //优惠券信息 couponData id:couponId  money:couponMoney
var orderData = sessionStorage.getItem("orderData");
var orderDataObj = JSON.parse(orderData);
var sdType = orderDataObj.Types;
var couponData = sessionStorage.getItem("couponData");
var couponMoney = orderDataObj.YouId,
    couponId = orderDataObj.YouMoney;
var nearBuy = sessionStorage.getItem("nearBuy");
// 闪电买取订单详情
if (sdType == "0") {
    //如果知道物品价格，则不能使用余额支付
    if (orderDataObj.ZhiPrice == "1") {
        $("#balance_pay").empty();
        $("#balance_pay").hide();
    }
    //就近买逻辑判断
    if (orderDataObj.Near == "0") {
        $("#start_add .content").html(orderDataObj.QuHuoAddress);
        $("#end_add .content").html(orderDataObj.ShouhuoAddress);
        if (orderDataObj.ZhiPrice == "0") {
            $("#res_money").css("display", "none")
        } else if (orderDataObj.ZhiPrice == "1") {
            $("#res_money .content").html("￥" + orderDataObj.WuPin_Money);
        }
        $("#desc .content").html("购买时间" + orderDataObj.Quhuo_Date + " " + orderDataObj.Desc);
        $("#user_tel .content").html(orderDataObj.Shouhuo_Tel);
    } else if (orderDataObj.Near == "1") {
        $("#start_add .content").html(orderDataObj.QuHuoAddress);
        $("#end_add .content").html(orderDataObj.ShouhuoAddress);
        if (orderDataObj.ZhiPrice == "0") {
            $("#res_money").css("display", "none")
        } else {
            $("#res_money .content").html("￥" + orderDataObj.WuPin_Money);
        }
        $("#desc .content").html("购买时间" + orderDataObj.Quhuo_Date + " " + orderDataObj.Desc);
        $("#user_tel .content").html(orderDataObj.Shouhuo_Tel);
    }
} else if (sdType == "1") {
    $("#start_add .name").html("取货地址");
    $("#start_add .content").html(orderDataObj.QuHuoAddress);
    $("#end_add .name").html("收货地址");
    $("#end_add .content").html(orderDataObj.ShouhuoAddress);
    $("#desc .content").html("取货时间" + orderDataObj.Quhuo_Date + " " + orderDataObj.Desc);
    $("#res_money").css("display", "none");
    $("#user_tel").css("display", "none");
} else if (sdType == "2") {
    $("#start_add .name").html("取货地址");
    $("#start_add .content").html(orderDataObj.QuHuoAddress);
    $("#end_add .name").html("收货地址");
    $("#end_add .content").html(orderDataObj.ShouhuoAddress);
    $("#desc .content").html("取货时间" + orderDataObj.Quhuo_Date + " " + orderDataObj.Desc);
    $("#res_money").css("display", "none");
    $("#user_tel").css("display", "none");
}
var paoMoney = Number(orderDataObj.OrderMonery) - Number(orderDataObj.WuPin_Money) - Number(orderDataObj.TouMoney); //服务费
$("#order_money").html(paoMoney + "元"); //服务费显示
if (couponData) {
    var couponDataObj = JSON.parse(couponData);
    //serveMoney 使用优惠券后的服务费       
    var serveMoney = paoMoney - Number(couponDataObj.YouMoney);
    serveMoney = (serveMoney < 0 ? serveMoney = 0 : serveMoney);
    var totalMoney = serveMoney + Number(orderDataObj.WuPin_Money) + Number(orderDataObj.TouMoney);
    couponMoney = Number(couponDataObj.YouMoney);
    couponId = couponDataObj.YouId;
    $("#total_money").html(totalMoney + "元(已优惠￥" + (couponMoney > paoMoney ? paoMoney : couponMoney) + ")");
} else {
    $("#total_money").html(orderDataObj.OrderMonery + "元(已优惠￥" + orderDataObj.YouMoney + ")");
}
//获取优惠券信息
$.ajax({
    type: "get",
    url: currentUrl + "/interfaceDOC/firstProject/User.ashx?action=Get_YouHuiQuan",
    data: {
        "UserId": orderDataObj.UserId
    },
    dataType: "json",
    success: function(data) {
        if (data.msgcode == "1") {
            // console.log(data);
            //可用优惠券数量显示   2017.7.17 GJC
            //canUseNum 可用优惠券数量 （服务费大于优惠券满减金额为可用）
            var canUseNum = 0;
            for (var i = 0; i < data.data.length; i++) {
                if (paoMoney >= data.data[i].OverMoney) {
                    canUseNum++;
                }
            }
            $("#coupon_num").html(canUseNum + "张可用");
        }

    },
    error: function(data) {
        console.log("获取优惠券失败");
    }
});
$("#coupon").click(function() {
    window.location.href = "../html/coupon.html";
    sessionStorage.setItem("couponClickOn", "true");
    sessionStorage.setItem("serveMoney", paoMoney);
})
var isPlaceOrder = false; //是否成功下单
$('.form_submit').click(function() {
    var OrderId = "";
    $(".form_submit").attr({ disabled: "disabled" });
    //if (isPlaceOrder == false && balancePay == true && wxPay == false) {
    $.ajax({
        type: "post",
        url: currentUrl + "/interfaceDOC/firstProject/User.ashx?action=Insert_OrderMSQ",
        data: {
            "Near": orderDataObj.Near,
            "Baowenxiang": orderDataObj.Baowenxiang,
            "QuHuoAddress": orderDataObj.QuHuoAddress,
            "Quhuo_Lng": orderDataObj.Quhuo_Lng,
            "Quhuo_Lat": orderDataObj.Quhuo_Lat,
            "Quhuo_Person": orderDataObj.Shouhuo_Person,
            "Quhuo_Tel": orderDataObj.Shouhuo_Tel,
            "ShouhuoAddress": orderDataObj.ShouhuoAddress,
            "Shouhuo_Lng": orderDataObj.Shouhuo_Lng,
            "Shouhuo_Lat": orderDataObj.Shouhuo_Lat,
            "Shouhuo_Person": orderDataObj.Shouhuo_Person,
            "Shouhuo_Tel": orderDataObj.Shouhuo_Tel,
            "GoodsId": orderDataObj.GoodsId,
            "ZhiPrice": orderDataObj.ZhiPrice,
            "WuPin_Money": orderDataObj.WuPin_Money,
            "Desc": $("#desc .content").html(),
            "YiSui": orderDataObj.YiSui,
            "Quhuo_Date": orderDataObj.Quhuo_Date,
            "YouId": couponId,
            "YouMoney": couponMoney,
            "OrderMonery": totalMoney,
            "CityId": orderDataObj.CityId,
            "UserId": orderDataObj.UserId,
            "Types": orderDataObj.Types,
            "IsTouBao": orderDataObj.IsTouBao,
            "TouMoney": orderDataObj.TouMoney,
            "PeiMoney": orderDataObj.PeiMoney,
        },
        dataType: "json",
        success: function(data) {
            if (data.msgcode == "1") {
                // console.log(data);
                OrderId = data.data.OrderId;
                sessionStorage.setItem("OrderId", OrderId);
                sessionStorage.setItem("OrderType", orderDataObj.Types);
                payOrder();
            } else {
                $.alert(data.msg);
                return false
            }
        },
        error: function() {
            $.alert("下单失败")
            return false
        },
        complete: function() {
            $(".form_submit").removeAttr("disabled");
        }
    });
    //} else if (isPlaceOrder == false && balancePay == false && wxPay == true) {
    //    $.ajax({
    //        type: "post",
    //        url: currentUrl + "/interfaceDOC/firstProject/User.ashx?action=Insert_OrderMSQ_WeiXin",
    //        data: {
    //            "Near": orderDataObj.Near,
    //            "Baowenxiang": orderDataObj.Baowenxiang,
    //            "QuHuoAddress": orderDataObj.QuHuoAddress,
    //            "Quhuo_Lng": orderDataObj.Quhuo_Lng,
    //            "Quhuo_Lat": orderDataObj.Quhuo_Lat,
    //            "Quhuo_Person": "旦旦",
    //            "Quhuo_Tel": "13115484689",
    //            "ShouhuoAddress": orderDataObj.ShouhuoAddress,
    //            "Shouhuo_Lng": orderDataObj.Shouhuo_Lng,
    //            "Shouhuo_Lat": orderDataObj.Shouhuo_Lat,
    //            "Shouhuo_Person": orderDataObj.Shouhuo_Person,
    //            "Shouhuo_Tel": orderDataObj.Shouhuo_Tel,
    //            "GoodsId": orderDataObj.GoodsId,
    //            "ZhiPrice": orderDataObj.ZhiPrice,
    //            "WuPin_Money": orderDataObj.WuPin_Money,
    //            "Desc": "微信测试",
    //            "YiSui": orderDataObj.YiSui,
    //            "Quhuo_Date": orderDataObj.Quhuo_Date,
    //            "YouId": "0",
    //            "YouMoney": "0",
    //            "OrderMonery": "0.01",
    //            "CityId": orderDataObj.CityId,
    //            "UserId": orderDataObj.UserId,
    //            "Types": orderDataObj.Types,
    //            "IsTouBao": "0",
    //            "TouMoney": "0",
    //            "PeiMoney": "0",
    //        },
    //        dataType: "json",
    //        success: function (data) {
    //            console.log(data);
    //            if (data.msgcode == "1") {
    //                console.log(data);
    //                isPlaceOrder == true;
    //                OrderId = data.data.OrderId;
    //                sessionStorage.setItem("OrderId", OrderId);
    //                sessionStorage.setItem("OrderType", orderDataObj.Types);
    //            } else {
    //                alert(data.msg);
    //                return false
    //            }
    //        },
    //        error: function () {
    //            alert("请求失败")
    //            return false
    //        }
    //    });
    //};
    //余额支付
    function payOrder() {
        if (isPlaceOrder == false && balancePay == true && wxPay == false && OrderId != "") {
            $.ajax({
                type: "post",
                url: currentUrl + "/interfaceDOC/firstProject/User.ashx?action=Inser_PayOrder",
                data: {
                    "OrderId": OrderId,
                    "YouHuiId": couponId
                },
                dataType: "json",
                beforeSend: function() {
                    $.showLoading("正在支付");
                },
                success: function(data) {
                    if (data.msgcode == "1") {
                        isPlaceOrder = true; //限制重复下单；
                        $('.mask').css("display", "block");
                        $('.pay_success').css("display", "block");
                        var countDown = parseInt(3);

                        function timeShow() {
                            countDown--;
                            $(".count_down").html(countDown);
                            if (countDown < 1) {
                                clearInterval(countdown);
                                $(".count_down").html("倒计时结束！！");
                                $('.mask').css("display", "none");
                                $('.pay_success').css("display", "none");
                                window.location.href = "../html/order_wait.html";
                            }
                        };
                        countdown = setInterval(timeShow, 1000);
                    } else {
                        $.alert(data.msg);
                        return false
                    }
                },
                error: function() {
                    $.alert("余额支付请求数据错误");
                    return false
                },
                complete: function() {
                    $.hideLoading();
                }
            });
        } else if (isPlaceOrder == false && balancePay == false && wxPay == true && OrderId != "") {
            //  微信支付
            $.ajax({
                type: 'post',
                url: currentUrl + '/WxSdjs/PayHandler.ashx',
                data: {
                    action: 'buy',
                    openId: localStorage.getItem("openId"),
                    orderId: 'x' + OrderId,
                    youHuiId: couponId
                },
                success: function(response) {
                    var result = JSON.parse(response);
                    if (result.IsOk) {
                        var wxJsApiParam = result.Data;
                        WeixinJSBridge.invoke('getBrandWCPayRequest',
                            JSON.parse(wxJsApiParam),
                            function(res) {
                                if (res.err_msg == "get_brand_wcpay_request:ok") {
                                    $('.mask').css("display", "block");
                                    $('.pay_success').css("display", "block");
                                    var countDown = parseInt(3);

                                    function timeShow() {
                                        countDown--;
                                        $(".count_down").html(countDown);
                                        if (countDown < 1) {
                                            clearInterval(countdown);
                                            $(".count_down").html("倒计时结束！！");
                                            $('.mask').css("display", "none");
                                            $('.pay_success').css("display", "none");
                                            window.location.href = "../html/order_wait.html";
                                        }
                                    };
                                    countdown = setInterval(timeShow, 1000);
                                }
                                // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                                //因此微信团队建议，当收到ok返回时，向商户后台询问是否收到交易成功的通知，若收到通知，前端展示交易成功的界面；若此时未收到通知，商户后台主动调用查询订单接口，查询订单的当前状态，并反馈给前端展示相应的界面。
                            });
                    }

                },
                error: function() {
                    $.alert('微信下单失败，请重试！');
                }
            });
            //location.href = "/WxSdjs/Pay.aspx?orderId=x" + OrderId + '&youHuiId=' + couponId;
        }
    }


})